#encoding=utf8    
import sys 

from zbus import Application, Message, Controller
from zbus import route, context, add_filter  


sys.path.append("../") 


def method_filter(req, res):
    print("in method filter", req, res)
    return True

def class_filter(req, res):   
    #res.set_cookie('test', 'mycookie; HttpOnly; Path=/;') 
    #print("in class filter", req, res) 
    return True

def auth_filter(req, res):  
    '''
    global filter
    '''  
    if req.url.startswith('/login/'): #exclude login checking
        return True
    
    user = req.get_cookie('user') 
    if user:
        print(user)
        return True
    
    print("in global(authentication) filter", req, res)  
    res.status = 403
    res.body = "Auth required"
    return False


class AuthFilter(Controller): 
    '''
    No need to extend from Controller to build a filter, 
    when extend from Controller, db and template are enabled by default
    '''
    def __call__(self, req, res):
        '''
        global filter
        '''  
        if req.url.startswith('/login/'): #exclude login checking
            return True
        
        user = req.get_cookie('user') 
        if user:
            print(user)
            return True
        
        print("in global(authentication) filter", req, res)  
        res.status = 403
        res.body = "Auth required"
        return False
    
@add_filter(class_filter)
class MyService: 
    
    def echo(self, ping):
        return str(ping)
     
    def plus(self, a, b):  
        return int(a) + int(b) 
     
    def testEncoding(self):  
        return u'中文'
     
    def ctx(self): 
        res = context.response
        res.status = 200
        res.body = 'hello from context'
        return res
     
    def login(self, user,  pwd): 
        res = context.response
        res.set_cookie('user', 'rushmore; Path=/;')
        return res
    
    @add_filter(method_filter)
    def noReturn(self):
        pass
    
    @route('/')
    def home(self):
        res = Message()
        res.status = 200
        res.headers['content-type'] = 'text/html; charset=utf8'
        res.body = '<h1> from Python </h1>'
        return res
    
    def getBin(self):
        b = bytearray(10)
        import base64
        return base64.b64encode(b).decode('utf8')
    
    def throwException(self):
        raise Exception("runtime exception from server")
    
    
    def map(self):
        return {
            'key1': 'mykey',
            'key2': 'value2',
            'key3': 2.5
        }

    #文件上传的例子
    def upload(self, req):
        import base64
        files = req['files']
        for f in files:
            data = files[f][0]['data']
            data = base64.b64decode(data)
            print(data)

        return 'ok'
    
    @route(path='/post', method=['GET', 'POST'])
    def post(self): 
        return {
            'key1': 'post required',
            'key2': 'post me',
            'key3': 122.3
        }
        
    def testTimeout(self):
        import time
        time.sleep(20) 
        
    def p(self, name, age=10, address='sz'):
        return {
            'name': name,
            'age': int(age),
            'address': address
        }
        
    def test(self, d): 
        return "OK-%s"%d


app = Application() 
app.mount('/', MyService()) #relative mount url  

#app.add_filter(AuthFilter()) #global filter 

app.run(url='localhost:15555')
